import React, {useEffect, useRef, useCallback, useState, useMemo} from 'react';
import {
  Image,
  InteractionManager,
  Keyboard,
  KeyboardAvoidingView,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import StickerContentPage from './StickerContentPage';
import StickerDataSQL from '../db';
import {
  TitleBar,
  SideBar,
  ModalCreateGroup,
  HeaderBtnBar,
  ModalStickerBtn,
} from '../components';
import {DB_ST} from '../utils/DBFields';
import NativeFileUtils from 'rtn-supernote-plugin-core/src/module/NativeFileUtils';
import NativeNoteTrails from 'rtn-supernote-plugin-core/src/module/NativeNoteTrails';
import NativeEvent from 'rtn-supernote-plugin-core/src/module/NativeEvent';
import {
  stickerGroupAdd,
  moveSticker,
  importSticker,
  renameFunGroup,
  delStickerGroup,
  delSticker,
  renameWithoutIDFun,
  renameSticker,
} from '../utils/StickerUtils';
import {zip, subscribe} from 'react-native-zip-archive';
import suffix from '../utils/suffix';
import i18n from '../i18n';
import NativeFileSelector from 'rtn-supernote-plugin-core/src/module/NativeFileSelector';
import {
  extractFileInfo,
  findNext2Em,
  parseNameJson,
  RegExpArr,
} from '../utils/jsUtils';
import stylesXS from '../styles/xs';
import stylesMD from '../styles/md';
import stylesLG from '../styles/lg';
import dimesA5 from '../styles/size/a5';
import dimesA5X2 from '../styles/size/a5x2';
import dimesA6 from '../styles/size/nom';
import nativeFileUtils from '../../node_change/RTNSuperNotePluginCore/src/module/NativeFileUtils';
import RNFS from 'react-native-fs';
import NativePluginManager from 'rtn-supernote-plugin-core/src/module/NativePluginManager';
import {SNUIUtils} from 'rtn-supernote-plugin-core'
const SMALL_KEYBOARD_HEIGHT = 200;
// A5X设置的键盘高度
const A5X_KEYBOARD_HEIGHT = 200;
// 用来判断是否是蓝牙键盘， 键盘的最小高度
const KEYBOARD_MIN_HEIGHT = 300;

// 键盘横屏固定高度
const KEYBOARD_HEIGHT_LAND = 434;
const KEYBOARD_HEIGHT_LAND_MAX = 528;
// 蓝牙键盘高度
const KEYBOARD_HEIGHT_BLUE = 73;

// let zipProgress = null;
// 存储导出的任务Map
let exportTaskMap = new Map();
// 导出任务Id计数
let exportTaskIdCount = 0;
let currentExportTaskId = 0;

const deleteGroupMaxNum = 100;
const deletStickerMaxNum = 3;
const StickerBasePage = ({
  appState,
  rotation,
  changeEvent,
  screenWidth,
  screenHeight,
  currentStickerGroup,
  onCurrentStickerGroup
}) => {
  console.log('StickerBasePage rotation:' + rotation);
  console.log("StickerBasePage appState:" + appState);
  const [stickerGroups, setStickerGroups] = useState([]);
  // 用户创建的贴纸库列表
  const [userStickerGroups, setUserStickerGroups] = useState([]);
  const [stickerItemList, setStickerItemList] = useState([]);
  const [stickerGroupItem, setStickerGroupItem] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalStickerBtnVisible, setModalStickerBtnVisible] = useState(false);
   //1 新增 2 重命名 3 delete 4 progress 5 move 6 message have ok btn
   // 62 导出失败，63 导入失败
  const [modalUseStatus, setModalUseStatus] = useState(null);
  const [modalTitle, setModalTitle] = useState('');
  const [modalMessage, setModalMessage] = useState('');
  const [valueNm, setValueNm] = useState('');
  const [searchNm, setSearchNm] = useState('');
  const [headerStatus, setHeaderStatus] = useState(true);
  const [count, setCount] = useState(0);
  const [selectedStickerList, setSelectedStickerList] = useState([]);
  const [cancelData, setCancelData] = useState(null);
  const [overStatus, setOverStatus] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isToast, setToast] = useState(false);
  const [toastText, setToastText] = useState("");
  const [inputStatus, setInputStatus] = useState(false);
  // 是否输入特殊字符
  const [isInputSpecial, setIsInputSpecial] = useState(false);
  const timerRef = useRef(null);
  const textInputRef = useRef(null);

  const [isContentLoading, setIsContentLoading] = useState(false);
  const loadingContentTimerRef = useRef(null);

  // 设置键盘高度
  const [keyboardHeight, setKeyboardHeight] = useState(0);

  // 导入路径列表，重试导入用的
  const [importPathArr, setImportPathArr] = useState([]);

  const [scrollPosition, setScrollPosition] = useState(0);

  const recentIconString = Image.resolveAssetSource(require('../../assets/ic_recent.png')).uri.toString();

  let wd = Math.round(screenWidth);
  const styles =
    wd === 1024 || wd === 1365
      ? stylesLG
      : wd === 994 || wd === 1325
      ? stylesMD
      : stylesXS;
  const nom = wd === 1024 || wd === 1365
    ? dimesA5X2
    : wd === 994 || wd === 1325
      ? dimesA5
      : dimesA6;

  const isSmall = wd === 1024 || wd === 1365 || wd === 994 || wd === 1325
    ? false : true;
  const keyBehavior = wd === 1024 || wd === 1365
    ? "padding" : "none";
  const isA5X2 = wd === 1024 || wd === 1365;
  const isA5X = wd === 994 || wd === 1325;

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      (e) => {
        console.log("keyboardDidShow", e.endCoordinates.height);
        if ((rotation == 1 || rotation == 3) && !isA5X2) {
          const currentKeyHeight = Math.floor(e.endCoordinates.height);
          console.log("keyboardDidShow currentKeyHeight", currentKeyHeight);
          // KEYBOARD_HEIGHT_LAND是虚拟软键盘横屏状态下的固定高度，
          // 1.当前键盘高度小于KEYBOARD_MIN_HEIGHT说明是蓝牙键盘，键盘高度设置为0
          // 2.当前键盘高度大于KEYBOARD_HEIGHT_LAND，说明再蓝牙键盘关闭状态中，也要设置为0，否则界面显示会异常
          if (currentKeyHeight < KEYBOARD_MIN_HEIGHT
            /*  || (currentKeyHeight > KEYBOARD_HEIGHT_LAND && currentKeyHeight < KEYBOARD_HEIGHT_LAND_MAX) */
          ) {
            console.log("keyboardDidShow set 0");

            setKeyboardHeight(0);

          } else {
            setKeyboardHeight(isSmall ? SMALL_KEYBOARD_HEIGHT : A5X_KEYBOARD_HEIGHT);
          }

        }


      }
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        console.log("keyboardDidHide");
        if ((rotation == 1 || rotation == 3) && !isA5X2) {
          setKeyboardHeight(0);
        }

      }
    );

    return () => {
      keyboardDidHideListener.remove();
      keyboardDidShowListener.remove();
    };

  }, [rotation]);

  useEffect(() => {
    console.log("setIsLoading true");
    setIsLoading(true);

    setTimeout(() => {
      setIsLoading(false);
    }, 300);

  }, [rotation]);
  // useEffect(() => {
    
  // }, [isLoading]);
  useEffect(() => {
    _getStickerGroupList(currentStickerGroup);
  }, []);
  /*
   * 查询全部的贴纸库
   * */
  const _getStickerGroupList = async (groupItem = null) => {
    try {
      const {data} = await StickerDataSQL.db_fun(
        DB_ST.SELECT_STICKER_GROUP_CREATE_ST,
        [],
      );
      const res = await StickerDataSQL.db_default_fun(
        DB_ST.SELECT_STICKER_GROUP_CREATE_ST,
        [],
      );
      let defaultData = res?.data.map(item => {
        let langName = item.name;
        langName = parseNameJson(item.name)
        return { ...item, isDefault: true, langName: langName, };
      });
      setUserStickerGroups(data);
      
      let recent = await recentStickerData();
      let groupArr = [recent, ...defaultData, ...data]
      setStickerGroups(groupArr);
      console.log('stickerGroupList', groupArr);
      let arr = null;
      if (groupItem != null) {
        arr = groupArr?.filter(item => item.id === groupItem?.id
          && item?.isDefault === groupItem?.isDefault
        );
      }
      let currentGroupIndex = groupArr?.findIndex(item => item.id === currentStickerGroup?.id
        && item?.isDefault === currentStickerGroup?.isDefault
      );
      if(currentGroupIndex >= 0) {
        setScrollPosition(currentGroupIndex);
      }
      if (arr?.length > 0) {
        _getStickerItemList(arr[0]);
        setStickerGroupItem(arr[0]); 
      } else {
        setStickerItemList(recent?.data);
        setStickerGroupItem(recent);
      }
    } catch (error) {
      console.error('Error fetching sticker groups:', error);
    }
  };
  useEffect(() => {
    return () => {
      stopTimer();
    };
  }, []);
  useEffect(() => {
    if (overStatus) {
      if (exportTaskMap.get(currentExportTaskId)) {
        let ar = [];
        cancelData?.data?.map(item => {
          ar.push(item?.id);
        });
        console.log(ar, 'arrarrarrarrarr');
        delStickerGroup(
          ar,
          DB_ST.DELETE_GROUP_STICKERS_ST,
          stickerGroupItem,
          headerStatus,
        ).then(res => {
          console.log(res, 'arrarrarrarr');
        });
        setTimeout(() => {
          setModalUseStatus(null);
          setCount(0);
          setOverStatus(false);
          setCancelData(null);
          exportTaskMap.set(currentExportTaskId, false);
        }, 100);
        return;
      }
      let arr = cancelData?.data;
      arr?.length > 0 && _getStickerGroupList(arr[0]);
      setTimeout(() => {
        setModalVisible(false);
        setModalUseStatus(null);
        setCancelData(null);
        setCount(0);
        setOverStatus(false);
      }, 100);
    }
  }, [overStatus]);
  const startTimer = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    timerRef.current = setInterval(() => {
      setCount(prevCount => prevCount + 0.05);
    }, 100); // 每秒更新一次
  };
  const stopTimer = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null; // 清理ref中的定时器ID
    }
  };

  const startContentLoading = () => {
    if(loadingContentTimerRef.current) {
      clearTimeout(loadingContentTimerRef.current);
    }
    loadingContentTimerRef.current = setTimeout(function () {
      setIsContentLoading(false);
      loadingContentTimerRef.current = null;
    },100);
  };
  const stopContentLoading = () =>{
    if(loadingContentTimerRef.current) {
      clearTimeout(loadingContentTimerRef.current);
      loadingContentTimerRef.current = null;
    }
  };

  // 获取创建时间，创建时间是用来排序的，
  // 如果用户改了时间，当前时间可能比数据库中的时间小，需要重新设置
  const _getCreateTime = () => {
    const currentTime = Date.now();
    if(userStickerGroups?.length > 0) {
      if(currentTime < userStickerGroups[0]?.create_time) {
        return userStickerGroups[0]?.create_time + 100;
      }
    }
    return currentTime;
  }

  // 设置阻止休眠和侧滑条的状态
  const _setSlideAndSleepState = async (enable) => {
    try {
      //启用或关闭休眠
      await NativeEvent.setSystemDormancyState(enable);
      // 锁定侧滑条，或解锁侧滑条
      await NativeEvent.setStatusBarAndSlideBarState(enable);

    } catch (e) {
      console.error("_setSlideAndSleepState error:", e);
    }

  }


  // 获取最近贴纸数据
  const _getRecentStickerData = async () => {
    try {
      let {code, data} = await StickerDataSQL.db_fun(
        DB_ST.SELECT_STICKER_DS_ST,
        [],
      );
      // 获取内置贴纸的最近使用
      let systemData = await StickerDataSQL.db_default_fun(
        DB_ST.SELECT_STICKER_DS_ST,
        [],
      );
      if (systemData?.data?.length > 0) {
        // 设置内置贴纸数据isDefult为true
        let systemArr = systemData?.data?.map(item => {
          let langName = parseNameJson(item.name);
          return {...item, isDefault: true, langName: langName};
        });
        data = [...data, ...systemArr];
      }
      data.sort((a, b) => b.use_time - a.use_time);

      return data;
    } catch (e) {
      console.error('_getRecentStickerData error:' + e);
    }
  };

  const recentStickerData = async () => {
    try {
      let data = await _getRecentStickerData();
      console.log(data, 'SELECT_STICKER_DS_ST');
      return {
        id: 'recent',
        name: i18n.t('title.recent'),
        num: -1,
        thumb_sticker: recentIconString,
        data,
      };
    } catch (e) {}
  };

  /*
   *删除贴纸库
   * */
  const stickerGroupDel = async (ids, ty = true) => {
    const timer = setTimeout(()=>{
      setToastText(i18n.t('title.deleting'));
      setToast(true);
    },500);
    console.log("stickerGroupDel test start");
    // 获取下一个贴纸库的index
    var nextIndex = stickerGroups?.findIndex(item => item.id === ids[0]) + 1;
    if (nextIndex >= stickerGroups.length) {
      nextIndex = 1;
    }
    let nextGroup =
      stickerGroups[nextIndex];
    await _setSlideAndSleepState(true);
    const { code, data } = await delStickerGroup(
      ids,
      DB_ST.DELETE_GROUP_STICKERS_ST,
      stickerGroupItem,
      headerStatus,
    ); 
    if (code === 200) {
      await _getStickerGroupList(nextGroup || null);
    }
    console.log("stickerGroupDel test end");
    clearTimeout(timer);
    setToast(false);
    _setSlideAndSleepState(false);
  };

  const focusTextInput = (isModal= false) => {
    InteractionManager.runAfterInteractions(() => {
      setTimeout(()=>{
        console.log("ModalStickerBtn textInputRef:"+textInputRef.current);
        if(textInputRef.current) {
          if(isModal) {
            textInputRef?.current?.blur();
          }
          textInputRef?.current?.focus();
          textInputRef.current.setNativeProps({
            selection: {
              start: valueNm?.length,
              end: valueNm?.length,
            },
          });
        }
        
      },300);
    })
    
  };
/*   const focusTextInput = useCallback(() => {
    console.log("focusTextInput textInputRef:"+textInputRef.current);
    if (textInputRef) {
      setTimeout(() => {
        console.log("focusTextInput focus textInputRef:"+textInputRef.current);
        textInputRef?.current?.focus();
        textInputRef.current.setNativeProps({
          selection: {
            start: valueNm?.length,
            end: valueNm?.length,
          },
        });
      }, 200); // 根据需要调整延迟时间
    }
  }, [valueNm]); */

  const countFun = (ty = true) => {
    setCount(0.1);
    setTimeout(() => {
      setCount(0.25);
    }, 50);
    setTimeout(() => {
      setCount(0.5);
    }, 100);
    setTimeout(() => {
      setCount(0.75);
    }, 150);
    setTimeout(() => {
      setCount(0.9);
    }, 250);
    setTimeout(() => {
      setCount(1);
      setTimeout(() => {
        ty ? setModalVisible(false) : null;
        setCount(0);
      }, 100);
    }, 400);
  };
  /*
   *删除贴纸
   * */
  const stickerDel = async () => {
    
    console.log("stickerDel test start");
    let checkList = stickerItemList?.filter(item => item?.status);
    let ids = checkList?.map(item => item?.id);
    setModalVisible(false);
    const timer = setTimeout(()=>{
      setToastText(i18n.t('title.deleting'));
      setToast(true);
    },500);
    
    
    _setSlideAndSleepState(true);
    // countFun();
    const {code, data} = await delSticker(
      ids,
      DB_ST.DELETE_STICKERS_ST,
      stickerGroupItem,
      checkList,
      headerStatus,
      progress=>{
        console.log("stickerDel progress:"+progress);
      }
    );
    console.log("stickerDel test end");
    if (code === 200) {
      await _getStickerGroupList(stickerGroupItem);
      setHeaderStatus(true);
    }
    clearTimeout(timer);
    setToast(false);
    
    // setCount(0);
    // setTimeout(() => {
    //   setCount(0);
    // }, 100);
    _setSlideAndSleepState(false);
  };

  /*
   *更新贴纸库
   * */
  const stickerGroupUp = async groupName => {
    // 避免重复名称
    let newName = await renameWithoutIDFun(
      groupName,
      stickerGroupItem?.id,
      DB_ST.SELECT_STICKER_GROUP_LIKE_WITHOUT_ID_ST,
    );
    const {code, data} = await StickerDataSQL.db_fun(
      DB_ST.UPDATE_GROUP_STICKER_ST,
      [newName, stickerGroupItem?.id],
    );
    if (code === 200) {
      setModalVisible(false);
      await _getStickerGroupList(stickerGroupItem);
    }
  };

  // 更新内置贴纸数据
  const systemStickerUp = async (db_st, args) => {
    const {code, data} = await StickerDataSQL.db_default_fun(db_st, args);
    if (code === 200) {
      setHeaderStatus(true);
      // await _getStickerGroupList(stickerGroupItem);
    }
  };

  /*
   *更新贴纸
   * */
  const stickerUp = async (db_st, args) => {
    const {code, data} = await StickerDataSQL.db_fun(db_st, args);
    if (code === 200) {
      setHeaderStatus(true);
      await _getStickerGroupList(stickerGroupItem);
    }
  };
  const stickerUpReset = async (db_st, nm, data) => {
    console.log("stickerUpReset");
    // 避免重复名称
    let newName = await renameSticker(nm,
          DB_ST.SELECT_STICKER_LIKE_ST_BY_GROUP_ID,
          data?.sticker_group_id,
          data?.id
        );
    console.log("stickerUpReset newName:"+newName);
    await stickerUp(db_st, [
      newName,
      data?.path?.replace(data?.name, newName),
      data?.id,
    ]);
    nativeFileUtils.renameToFile(
      data?.path,
      data?.path.replace(data?.name, newName),
    );
  };

  /*
   *添加贴纸库
   * */
  const _stickerGroupAdd = async groupName => {
    let nm = groupName;
    if (!inputStatus) {
      nm = groupName.replace(/\s*\d*$/, '');
    }
    const {code, data} = await stickerGroupAdd(nm, null, _getCreateTime());
    console.log(data, 'stickerGroupAddstickerGroupAdd');
    if (code === 200) {
      _getStickerGroupList(data);
      setModalVisible(false);
      await NativeFileUtils.makeDir(data?.path);
      setInputStatus(false);
    }
  };

  const _getStickerItemList = async group => {
    try {
      const { code, data } = group.isDefault
        // 系统贴纸是按照id排序的，不可变
        ? await StickerDataSQL.db_default_fun(DB_ST.SELECT_STICKER_ORDER_ID, [
          group?.id,
        ])
        : await StickerDataSQL.db_fun(DB_ST.SELECT_STICKER_ST, [group?.id]);
      if (code === 200) {
        let arr = data?.map(item => {
          // 翻译名称
          let langName = item.name;
          if (group?.isDefault) {
            langName = parseNameJson(item.name);
          }
          return {
            ...item,
            status: false,
            isDefault: group?.isDefault,
            langName: langName,
          };
        });
        setStickerItemList([...arr]);
      }
    } catch (e) {}
  };
  //移动贴纸
  const _moveSticker = async data => {
    console.log("_moveSticker start");
   
    const re = await StickerDataSQL.db_fun(DB_ST.SELECT_STICKER_ST, [data?.id]);
    let checkList = stickerItemList?.filter(item => item?.status);
    let len = re?.data?.length + checkList?.length;
    if (len > 200) {
      setModalVisible(true);
      setModalUseStatus(61);
      setModalTitle(i18n.t('title.moveErr'));
      setModalMessage(i18n.t('msg.moveStErr'));
      return;
    }
    const moveTimer = setTimeout(()=>{
      setModalUseStatus(54);
      setModalVisible(true);
      setModalTitle(i18n.t('title.moving'));
    }, 500);
    await _setSlideAndSleepState(true);
    const id = exportTaskIdCount++;
    currentExportTaskId = id;
    exportTaskMap.set(id, false);
    let sum = checkList?.length;
    let lastMoveTime = Date.now();
    for(let index = 0; index < sum; index++) {
      // 取消移动
      if(exportTaskMap.get(id)) {
        _setSlideAndSleepState(false);
        await _getStickerGroupList(stickerGroupItem);
        setTimeout(async () => {
          setModalVisible(false);
          setModalUseStatus(null);
          setHeaderStatus(true);
          setCount(0);
        }, 200);
        return;
      }
      let item = checkList[index];
      const res = await moveSticker(item, data, stickerGroupItem);
      if(Date.now() - lastMoveTime >=1000 || index +1 === sum) {
        setCount((index + 1) / sum);
      }
      if (checkList?.length === index + 1) {
        console.log("_moveSticker data end");
        
        setStickerGroupItem(data);
        onCurrentStickerGroup(data);
        clearTimeout(moveTimer);
        await _getStickerGroupList(data);
        setModalVisible(false);
        
        console.log("_moveSticker end");
        setTimeout(async () => {
          setModalUseStatus(null);
          setHeaderStatus(true);
          setCount(0);
        }, 200);
      }
      console.log("move sticker", index, res);
    }
    _setSlideAndSleepState(false);
  };
  /*
   * 展示贴纸库压缩包
   * */
  const selectSticker = async (nm = 'sticker') => {
    try {
      if (stickerGroups?.length >= 51) {
        setModalUseStatus(61);
        setModalVisible(true);
        setModalTitle(i18n.t('title.imFail'));
        setModalMessage(i18n.t('msg.newCollErr'));
        return;
      }
      const stickerData = await NativeFileSelector.selectFile({
        selectType: 2,
        suffixList: ['snstk'],
        maxNum: 51 - stickerGroups?.length,
        title: i18n.t('title.select'),
        rightButtonText: i18n.t('btn.import'),
        needSelectFolder: '/storage/emulated/0/EXPORT',
        limitPath: '/storage/emulated/0/EXPORT',
      });
      let pathArr = stickerData.map(extractFileInfo);
      if (pathArr?.length > 0) {
        setImportPathArr(pathArr);
        await _importSticker(pathArr);
      }
    } catch (e) {
      console.log(e, 'setSelectStickers');
    }
  };
  // const zipUnzipProgress = () => {
  //   console.log("zipUnzipProgress currentExportTaskId:"+currentExportTaskId);
  //   let lastZipProgressTime = 0;
  //   zipProgress = subscribe(async ({progress, filePath, zipId}) => {
  //     console.log(`progress: ${progress}\nprocessed at: ${filePath} zipId:${zipId}`);
  //     if(zipId != currentExportTaskId || exportTaskMap.get(currentExportTaskId)) {
  //       setCount(0);
  //       return;
  //     }
  //     if (Date.now() - lastZipProgressTime >= 500 || progress === 1) {
  //       lastZipProgressTime = Date.now();
  //       setCount(progress);
  //     }
  //     if (progress === 1) {
  //       if(zipProgress != null) {
  //         zipProgress.remove();
  //       }    
  //     }
  //   });
  // };
  /*
   * 导出贴纸库
   * */
  const _exportSticker = async () => {
    try {
      console.log("_exportSticker");
      const spaceSize = await NativeFileUtils.getStorageAvailableSpace();
      console.log('spaceSize', spaceSize);
      const disFile = await RNFS.readDir(stickerGroupItem?.path);
      let size = 0;
      disFile.map(item => {
        size += item.size;
      });
      console.log('dirSize', size);
      if (spaceSize < size * 3) {
        setModalUseStatus(61);
        setModalVisible(true);
        setModalTitle(i18n.t('title.exFail'));
        setModalMessage(i18n.t('msg.exportFail'));
        return;
      }
      await _setSlideAndSleepState(true);
      var id = exportTaskIdCount++;
      currentExportTaskId = id;
      exportTaskMap.set(id, false);
      console.log("_exportSticker id:" + id);

      const res = await NativeFileUtils.getExportPath();
      const data = await NativeFileUtils.listFiles(res) || [];
      setCancelData(null);
      let arr = [];
      data.map(item => {
        arr.push(extractFileInfo(item?.path));
      });
      let name = stickerGroupItem?.name;
      if (arr?.length > 0) {
        name = findNext2Em(arr, name, item => item.name);
      }
      setCancelData({ path: `${res}/${name}${suffix.sns}` });
      let lastZipProgressTime = 0;
      // 监听压缩进度
      const zipProgress = subscribe(async ({ progress, filePath, zipId }) => {
        console.log(`exportSticker progress: ${progress}\nprocessed at: ${filePath} zipId:${zipId} 
          currentExportTaskId:${currentExportTaskId}`);
        if (zipId != currentExportTaskId) {
          // 当前id和压缩id对应上了，需要取消进度监听，因为zipID不是导出id，不需要更新进度
          // 因为可能同时存在两个压缩线程，需要区分当前哪个线程是当前导出线程，哪个线程是已经被取消的线程
          if (zipId == id) {
            zipProgress.remove();
          }
          return;
        }
        if (Date.now() - lastZipProgressTime >= 500 || progress === 1) {
          lastZipProgressTime = Date.now();
          setCount(progress);
        }
        if (progress === 1) {
          if (zipProgress != null) {
            zipProgress.remove();
          }
        }
      });
      var tempZipPath = await NativePluginManager.getPluginDirPath();
      tempZipPath = tempZipPath + '/cache';
      // 清空缓存
      await NativeFileUtils.deleteDir(tempZipPath);
      // 创建缓存目录
      await NativeFileUtils.makeDir(tempZipPath);
      tempZipPath = tempZipPath + "/" + Date.now() + suffix.sns;

      // `${stickerGroupItem?.path}/${name}${suffix.sns}`;

      // 删除上一次的临时压缩文件，保证缓存不会过大
      await NativeFileUtils.deleteFile(tempZipPath);
      zip(
        stickerGroupItem?.path,
        tempZipPath,
        id
      )
        .then(async path => {
          if (zipProgress != null) {
            zipProgress.remove();
          }
          if (exportTaskMap.get(id)) {
            console.log("_exportSticker cancel id:" + id + "=="+currentExportTaskId);
            if (id === currentExportTaskId) {
              setCount(0);
              _setSlideAndSleepState(false);
            }
            exportTaskMap.delete(id);
            NativeFileUtils.deleteFile(path);
            return;
          }
          await NativeFileUtils.copyFile(path, `${res}/${name}${suffix.sns}`);
          NativeFileUtils.deleteFile(path);
          setModalUseStatus(6);
          setModalTitle(i18n.t('title.exCom'));
          setModalMessage(`${i18n.t('msg.exportCom')}${name}${suffix.sns}`);
          if (id === currentExportTaskId) {
            setCount(0);
            _setSlideAndSleepState(false);
          }
        })
        .catch(error => {
          if (id === currentExportTaskId) {
            _setSlideAndSleepState(false);
          }
          setModalUseStatus(62);
          setModalTitle(i18n.t('title.exFail'));
          setModalMessage(i18n.t('msg.failedExport'));
          setCount(0);
          console.error(error, 'zipUnzipProgress');
        });
    } catch (e) {
      console.log(e, 'extractFileInfoextractFileInfos');
      setModalUseStatus(62);
      setModalVisible(true);
      setModalTitle(i18n.t('title.exFail'));
      setModalMessage(i18n.t('msg.failedExport'));
      setCount(0);
      if(tempZipPath){
        NativeFileUtils.deleteFile(tempZipPath);
      }
      if (id === currentExportTaskId) {
        _setSlideAndSleepState(false);
      }  
    }
  };
  /*
   * 导入贴纸库
   * */
  const _importSticker = async item => {
    try {
      if (!item || item.length === 0) {
        return;
      }
      const spaceSize = await NativeFileUtils.getStorageAvailableSpace();
      console.log('spaceSize', spaceSize);
      let importSize = 0;
      for (let ite of item) {
        const isExists = await RNFS.exists(ite?.path);
        if(!isExists) {
          setModalUseStatus(61);
          setModalVisible(true);
          setModalTitle(i18n.t('title.imFail'));
          setModalMessage(i18n.t('msg.importFileEmpty'));
          return;
        }
        const {size} = await RNFS.stat(ite?.path);
        importSize = importSize + size;
      }
      console.log('dirSize', importSize);
      if (spaceSize < importSize * 3) {
        setModalUseStatus(61);
        setModalVisible(true);
        setModalTitle(i18n.t('title.imFail'));
        setModalMessage(i18n.t('msg.exportFail'));
        return;
      }
      await _setSlideAndSleepState(true);
      const id = exportTaskIdCount++;
      currentExportTaskId = id;
      exportTaskMap.set(id, false);
      setCancelData(null);
      setModalUseStatus(41);
      setModalVisible(true);
      setModalTitle(i18n.t('title.import'));
      let newArr = [];
      // 导入总进度
      let mainProgress = 0;
      setCount(mainProgress);
      for (let index = 0; index < item.length; index++) {
        mainProgress = index / item.length;
        setCount(mainProgress);
        // 当前单个进度
        let segProgress = 0;
        const ite = item[index];
        // startTimer();
        // 解压进度
        let unzipProcess = 0;
        // 插入数据库进度
        let insertDBProgress = 0;

        let unzipProgress = subscribe(async ({progress, filePath}) => {
          // 实际进度需要分割一下，保证进度跳准确
          unzipProcess = progress / 2;
          setCount(
            mainProgress +
              unzipProcess / item.length +
              insertDBProgress / item.length,
          );
          if (progress === 1) {
            unzipProgress.remove();
          }
        });
        const res = await importSticker(
          ite,
          exportTaskMap,
          id,
          process => {
            insertDBProgress = process / 2;
            setCount(
              mainProgress +
                unzipProcess / item.length +
                insertDBProgress / item.length,
            );
            console.log('_importSticker db process:' + process);
          },
          _getCreateTime()
        );
        unzipProgress.remove();
        // 导出被取消了
        if (res?.code === 300) {
          setImportPathArr(null);
          stopTimer();
          setCount(0);
          if (index >= 1) {
            newArr = newArr.reverse();
            _getStickerGroupList(newArr[0]);
          }
          _setSlideAndSleepState(false);
          return;
        }


        // 导入报错，合集文件被修改过，或文件不存在
        if (res?.code === 400 || res.code === 500) {
          stopTimer();
          setModalUseStatus(61);
          setModalTitle(i18n.t('title.imFail'));
          setModalMessage(res?.code === 400
            ? i18n.t('msg.importFileErr')
            : i18n.t('msg.importFileEmpty'));
          setCount(0);
          if (index >= 1) {
            newArr = newArr.reverse();
            _getStickerGroupList(newArr[0]);
          }
          _setSlideAndSleepState(false);
          break;
        }
        newArr.push(res?.data || null); // Provide default value if data is undefined
        res?.list?.map((it, idx) => {
          if (idx + 1 === res?.list?.length) {
            stopTimer();
            setCount(1);
          }
        });

        if (index + 1 === item?.length) {
          setImportPathArr(null);
          stopTimer();
          setCount(1);
          setCancelData({data: newArr.reverse()}); // Reverse the array after pushing all elements
          setOverStatus(true);
        }
      }
      _setSlideAndSleepState(false);
    } catch (e) {
      stopTimer();
      setModalVisible(true);
      setModalUseStatus(63);
      setModalTitle(i18n.t('title.imFail'));
      setModalMessage(i18n.t('msg.failedImport'));
      setCount(0);
      _setSlideAndSleepState(false);
      console.error('Error during sticker import:', e);
    }
  };
  const _searchSticker = async nm => {
    let {code, data} = await StickerDataSQL.db_fun(
      DB_ST.SELECT_STICKER_LIKE_ST,
      [`%${nm}%`],
    );
    // 搜索内置贴纸数据
    let systemData = await StickerDataSQL.db_default_fun(
      DB_ST.SELECT_STICKER_LIKE_ST,
      [`%${nm}%`],
    );
    if (systemData?.data?.length > 0) {
      // 设置内置贴纸数据isDefult为true
      let systemArr = [];
      for (let item of systemData.data) {
        let langName = parseNameJson(item.name);
        if (langName?.toLowerCase().includes(nm?.toLowerCase())) {
          systemArr.push({...item, isDefault: true, langName: langName});
        }
      }
      data = [...data, ...systemArr];
    }
    // 排序
    data.sort((a, b) => a.name.localeCompare(b.name));

    setStickerItemList(data);
  };
  const _onConfirm = nm => {
    console.log("_onConfirm nm:"+nm);
    let checkList = stickerItemList?.filter(item => item?.status);
    if (headerStatus) {
      if (modalUseStatus === 1) {
        if (stickerGroups?.length >= 51) {
          return;
        }
      }
      modalUseStatus === 1
        ? _stickerGroupAdd(nm)
        : modalUseStatus === 2
        ? stickerGroupUp(nm)
        : modalUseStatus === 3
        ? stickerGroupDel([stickerGroupItem.id])
        : modalUseStatus === 6
        ? NativeFileUtils.openFilePath(cancelData?.path)
        : modalUseStatus === 7
        ? clearRecent()
        : null;
      if (modalUseStatus === 6) {
        setModalUseStatus(null);
      }
     
      
      if (modalUseStatus === 62) {
        setModalStickerBtnVisible(false);
        setModalUseStatus(42);
        setModalVisible(true);
        setModalTitle(i18n.t('title.export'));
        _exportSticker();
        return;
      }
      if(modalUseStatus === 63) {
        _importSticker(importPathArr);
        return;
      }
      setModalVisible(false);
    } else {
      setModalVisible(false);
      if (modalUseStatus === 5) {
        setHeaderStatus(true);
      }
      modalUseStatus === 2
        ? stickerUpReset(DB_ST.UPDATE_STICKER_NM_ST, nm, checkList[0])
        : modalUseStatus === 3
        ? stickerDel(checkList?.map(item => item?.id))
        : modalUseStatus === 5
        ? _moveSticker(nm)
        : null;
    }
  };
  const clearRecent = async () => {
    stickerItemList?.map(async item => {
      await StickerDataSQL.db_fun(DB_ST.UPDATE_STICKER_USE_TIME_ST, [
        0,
        item?.id,
      ]);
      await StickerDataSQL.db_default_fun(DB_ST.UPDATE_STICKER_USE_TIME_ST, [
        0,
        item?.id,
      ]);
    });
    setStickerItemList([]);
  };
  const _onUp = async () => {
    let checkList = stickerItemList?.filter(item => item?.status);
    let checkIds = checkList?.map(item => item?.id);
    const re = await stickerUp(DB_ST.UPDATE_STICKER_UPDATE_TIME_ST, [
      Date.now(),
      checkIds[0],
    ]);

    const res = await stickerUp(DB_ST.UPDATE_GROUP_STICKER_THUMB_ST, [
      checkList[0]?.thumb_sticker,
      stickerGroupItem?.id,
    ]);
    if (res?.code === 200) {
      setTimeout(async () => {
        await _getStickerGroupList(stickerGroupItem);
      }, 300);
    }
  };
  const cancelProgress = () => {
    setModalVisible(false);
    setCount(0);
    exportTaskMap.set(currentExportTaskId, true);
    _setSlideAndSleepState(false);
  };

  return (
    <View style={styles.container}>
      {headerStatus ? (
        <TitleBar
          backgroundColor={'#fff'}
          textColor={'#000'}
          onBack={async () => {
            changeEvent();
            await NativeEvent.onStop();
          }}
          title={i18n.t('title.sticker')}
          screenWidth={screenWidth}
          screenHeight={screenHeight}
          status={'base'}
          sWidth={{width: screenWidth}}
        />
      ) : (
        <HeaderBtnBar
          list={selectedStickerList}
          listLen={stickerItemList.length}
          onCancel={() => {
            setHeaderStatus(true);
            setTimeout(() => {
              setStickerItemList(
                stickerItemList.map(item => {
                  return {...item, status: false};
                }),
              );
            }, 200);
          }}
          screenWidth={screenWidth}
          screenHeight={screenHeight}
          onReset={() => {
            let checkList = stickerItemList?.filter(item => item?.status);
            if (checkList?.length === 1) {
              console.log("onReset");
              let obj = checkList[0];
              setValueNm(obj?.name);
              setModalTitle(i18n.t('title.renameSt'));
              setModalMessage(i18n.t('placeholder.sticker'));
              setModalUseStatus(2);
              focusTextInput();
            }
          }}
          onUp={async () => {
            let checkList = stickerItemList?.filter(item => item?.status);
            let checkIds = checkList?.map(item => item?.id);
            if (checkIds?.length === 1) {
              await _onUp();
            }
          }}
        onDel={async () => {
          try {
            let re = await SNUIUtils.showRattaDialog(
              i18n.t('msg.delStickerHead') + selectedStickerList.length
              + i18n.t('msg.delStickerEnd'),
              i18n.t('btn.cancel'),
              i18n.t('btn.delete'),
              false
            );
            let checkList = stickerItemList?.filter(item => item?.status);
            re ? stickerDel() : null;

          } catch (e) {
            console.log("delet sticker error", e);
          }
          //   setModalUseStatus(3);
          //   setModalVisible(true);
          //   setModalTitle(i18n.t('title.tips'));
          //   setModalMessage(i18n.t('msg.delStickerHead') + selectedStickerList.length
          // + i18n.t('msg.delStickerEnd'));
          }}
          onCheckAll={() => {
            let len = stickerItemList?.filter(item => item?.status)?.length;

            var newList = stickerItemList.map(item => {
              return {
                ...item,
                status: len === stickerItemList?.length ? false : true,
              };
            });
            setStickerItemList(newList);
            if (len == stickerItemList?.length) {
              setSelectedStickerList([]);
            } else {
              setSelectedStickerList(newList);
            }
          }}
          onMove={() => {
            setModalUseStatus(5);
            setModalVisible(true);
            setModalTitle(i18n.t('title.moveTo'));
          }}
          checkStatus={
            stickerItemList?.length ===
            stickerItemList?.filter(item => item?.status)?.length
          }
        />
      )}
      <View style={{flexDirection: 'row', justifyContent: 'flex-start'}}>
        <SideBar
          appState={appState}
          stickerGroups={stickerGroups}
          screenWidth={screenWidth}
          screenHeight={screenHeight}
          scrollPosition={scrollPosition}
          from={'base'}
          add={async () => {
            console.log('add stickerGroups?.length:' + stickerGroups?.length);
            if (stickerGroups?.length >= 51) {
              setModalUseStatus(61);
              setModalVisible(true);
              setModalMessage(i18n.t('msg.newCollErr'));
              setModalTitle(i18n.t('title.newCollErr'));
            } else {
              if(modalVisible || modalUseStatus === 1) {
                return
              }
              setTimeout(() => {
                setStickerItemList(
                  stickerItemList.map(item => {
                    return {...item, status: false};
                  }),
                );
              }, 200);
              let collName = await renameFunGroup(
                i18n.t('placeholder.newColl'),
                DB_ST.SELECT_STICKER_GROUP_LIKE_ST,
              );
              setValueNm(collName);
              !headerStatus ? setHeaderStatus(true) : null;
              setModalTitle(i18n.t('title.newColl'));
              setModalMessage(i18n.t('placeholder.group'));
              setModalUseStatus(1);
              focusTextInput();
            }
          }}
          onImportPress={() => {
            if (stickerGroups?.length >= 51) {
              setModalUseStatus(61);
              setModalVisible(true);
              setModalMessage(i18n.t('msg.newCollErr'));
              setModalTitle(i18n.t('title.imFail'));
              return;
            }
            selectSticker('snstk');
            setTimeout(() => {
              setStickerItemList(
                stickerItemList.map(item => {
                  return {...item, status: false};
                }),
              );
            }, 200);
            setHeaderStatus(true);
          }}
          onItemPress={async data => {
            console.log("sidebar onItemPress data id:"+data?.id+"==="+stickerGroupItem?.id);
            setHeaderStatus(true);
            if(data?.id === stickerGroupItem?.id
              && data?.isDefault == stickerGroupItem?.isDefault
            ) {
              return;
            }
            setIsContentLoading(true);
            
            setStickerGroupItem(data);
            if (data?.id === 'search') {
              searchNm ? await _searchSticker(searchNm) : setStickerItemList([]);
              onCurrentStickerGroup(null);
            } else if (data?.id === 'recent') {
              onCurrentStickerGroup(null);
              setStickerItemList(await _getRecentStickerData());
            } else {
              onCurrentStickerGroup(data);
              await _getStickerItemList(data);
            }
            startContentLoading();
          }}
          stickerGroupId={
            stickerGroupItem?.isDefault
              ? -stickerGroupItem?.id
              : stickerGroupItem?.id
          }
        />
        <StickerContentPage
          stickerGroupItem={stickerGroupItem}
          isContentLoading={isContentLoading}
          list={stickerItemList}
          screenWidth={screenWidth}
          screenHeight={screenHeight}
          moreVisible={modalStickerBtnVisible}
          rotation={rotation}
          onItemPress={async data => {
            
            const re = await NativeNoteTrails.insertSticker(data?.path);
            if (re) {
              changeEvent();
              NativeEvent.onStop();
              if (data?.isDefault) {
                await systemStickerUp(DB_ST.UPDATE_STICKER_USE_TIME_ST, [
                  Date.now(),
                  data?.id,
                ]);
              } else {
                await stickerUp(DB_ST.UPDATE_STICKER_USE_TIME_ST, [
                  Date.now(),
                  data?.id,
                ]);
              }
              console.log("stickerbase test changeEvent");
              
            }
          }}
          onClearRecent={async () => {
            try {
              let re = await SNUIUtils.showRattaDialog(
                i18n.t('msg.clear'),
                i18n.t('btn.cancel'),
                i18n.t('btn.clear'),
                false
              );
              re ? clearRecent() : null;

            } catch (e) {
              console.log("onClearRecent error",error);

            }
            // setModalUseStatus(7);
            // setModalVisible(true);
            // setModalTitle(i18n.t('title.tips'));
            // setModalMessage(i18n.t('msg.clear'));
          }}
          onOpen={() => {
            if (!stickerGroupItem?.isDefault) {
              setModalStickerBtnVisible(!modalStickerBtnVisible);
              setHeaderStatus(true);
              setTimeout(() => {
                setStickerItemList(
                  stickerItemList.map(item => {
                    return {...item, status: false};
                  }),
                );
              }, 200);
            }
          }}
          onItemLongPress={item => {
            setHeaderStatus(false);
            if (item.status) {
              setSelectedStickerList([item]);
            }
          }}
          onCheckPress={data => {
            const selectedList = stickerItemList?.filter(item => item?.status);
            console.log(
              'onCheckPress selectedList:' + JSON.stringify(selectedList),
            );
            setSelectedStickerList(selectedList);
          }}
          onSearch={nm => _searchSticker(nm)}
          status={
            stickerGroupItem?.id === 'recent' ||
            stickerGroupItem?.id === 'search'
              ? stickerGroupItem?.id
              : 'content'
          }
          setSearchNm={setSearchNm}
          headerStatus={headerStatus}
        />
      </View>
      <ModalCreateGroup
        title={modalTitle}
        placeholder={modalMessage}
        modalVisible={modalVisible}
        stickerGroups={
          modalUseStatus === 5
            ? stickerGroups
                .filter(item => item?.id !== 'recent')
                ?.filter(
                  item => item?.id !== stickerGroupItem?.id && !item?.isDefault,
                )
            : stickerGroups.filter(item => item?.id !== 'recent')
        }
        stickerList={stickerItemList}
        onClose={() => {
          if (modalUseStatus === 41 || modalUseStatus === 42
            || modalUseStatus === 54
          ) {
            cancelProgress();
          } else {
            setModalUseStatus(null);
            setModalVisible(false);
            setValueNm('');
          }
        }}
        screenWidth={screenWidth}
        screenHeight={screenHeight}
        onConfirm={nm => _onConfirm(nm)}
        value={valueNm}
        progress={count}
        headerStatus={headerStatus}
        stickerGroupItem={stickerGroupItem}
        btnOk={
          modalUseStatus === 1
            ? i18n.t('btn.create')
            : modalUseStatus === 2 || modalUseStatus === 61
              ? i18n.t('btn.ok')
              : modalUseStatus === 3
                ? i18n.t('btn.delete')
                : modalUseStatus === 6
                  ? i18n.t('btn.jump')
                  : modalUseStatus === 7
                    ? i18n.t('btn.clear')
                    : modalUseStatus === 62
                      ? i18n.t('btn.export')
                      : modalUseStatus === 63
                        ? i18n.t('btn.import')
                        : null
        }
        message={''}
        status={modalUseStatus}
      />
      {modalUseStatus === 1 || modalUseStatus === 2 ? (
        <View
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: screenWidth,
            height: screenHeight,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
            <View
              style={[
                styles.modalBg,
                {
                  opacity: 0,
                  width: screenWidth,
                  height: screenHeight,
                },
              ]}
            />
          </TouchableWithoutFeedback>
            <View
              style={[
                styles.borderWidth,
                styles.borderRadius_6,
                styles.modalCardVertical,
              {
                backgroundColor: '#fff',
                marginBottom: (rotation == 1 || rotation == 3)
                  ? null : (isSmall ? nom.dp_px_300 : null),
                borderWidth: nom.dp_px_2 - nom.dp_px_1 / 2,
                top: (rotation == 1 || rotation == 3) ? screenHeight / 5 : null,
                position: (rotation == 1 || rotation == 3) ? 'absolute' : 'relative',
              },
              ]}>
              <View
                style={[
                  styles.modalCardTitle,
                  styles.bottomBorder,
                  styles.createNmHt,
                  {
                    borderBottomWidth: nom.dp_px_1
                  }
                ]}>
                <Text style={[styles.modalCardTitleText, styles.fontSize_40]}>
                  {modalTitle}
                </Text>
              </View>
              <View style={[styles.modalCardBody, styles.creatListHt_210]}>
                <View style={{position: 'absolute'}}>
                  <View
                    style={[
                      styles.modalTextInputCard,
                      styles.borderWidth,
                      styles.inputCard,
                    ]}>
                    <TextInput
                      style={[
                        styles.modalTextInputCard,
                        styles.inputCard,
                        styles.fontSize_34,
                        styles.paddingRl_20_100,
                        {
                          fontWeight: '400',
                          color: '#000',
                        },
                      ]}
                      ref={textInputRef}
                      selectTextOnFocus={false}
                      contextMenuHidden={true}
                      autoFocus={true}
                      caretHidden={true}
                      editable={true}
                      // maxLength={150}
                      placeholder={modalMessage}
                      multiline={false}
                      numberOfLines={1}
                      onChangeText={e => {
                        /* if (/^\s*$/.test(e)) {
                          setValueNm('');
                          return;
                        } */
                        const pattern = RegExpArr.special;
                        var matchTxt = e.match(pattern);

                        if (matchTxt) {
                          console.log(
                            'onChangeText matchTxt:' + JSON.stringify(matchTxt),
                          );
                          // 替换特殊字符
                          e = e.replace(matchTxt[0], '');
                          setIsInputSpecial(true);
                          setTimeout(() => {
                            setIsInputSpecial(false);
                          }, 3000);
                        }
                        setValueNm(e);
                        setInputStatus(true);
                      }}
                      onBlur={() => {
                        Keyboard.dismiss();
                      }}
                      value={valueNm}
                    />
                    {valueNm ? (
                      <TouchableWithoutFeedback
                        onPress={() => {
                          setValueNm('');
                        }}>
                        <Image
                          style={[styles.checkBtnWH, styles.closeBtn_88]}
                          source={require('../../assets/ic_close.png')}
                        />
                      </TouchableWithoutFeedback>
                    ) : null}
                    {isInputSpecial ? (
                      <View
                        style={[
                          styles.modalTextInputCard,
                          styles.inputCard,
                          {position: 'absolute', marginStart: 0, marginTop: 0},
                        ]}>
                        <Text
                          style={[
                            styles.modalTextInputCard,
                            styles.inputCard,
                            styles.fontSize_34,
                            styles.paddingRl_20_20,
                            {
                              fontWeight: '400',
                              color: '#fff',
                              backgroundColor: 'black',
                              textAlignVertical: 'center',
                            },
                          ]}>
                          {i18n.t('msg.specialToast')}
                        </Text>
                      </View>
                    ) : null}
                  </View>
                </View>
              </View>
              <View style={[styles.modalButtonCardStyle, styles.modalBtmCard,
                {
                  borderTopWidth: nom.dp_px_1
                }
              ]}>
                <TouchableWithoutFeedback
                  onPress={() => {
                    setValueNm('');
                    setModalUseStatus(null);
                  }}>
                  <View
                    style={[
                      styles.modalButtonStyle,
                      styles.modalCardBody,
                      styles.modalBoCard,
                      styles.borderWidth,{
                        minWidth:nom.dp_px_198,
                        width:null,
                        paddingHorizontal:nom.dp_px_32,
                        // 一旦有圆角，边框就会变粗，需要减一些值
                        borderWidth: nom.dp_px_2 - nom.dp_px_1 / 2,
                        overflow:'visible'
                      }
                    ]}>
                    <Text
                      numberOfLines={1}
                      style={[styles.modalButtonText, styles.fontSize_34,
                      {
                        textAlign:'center',
                        flexShrink:0
                      }
                      ]}>
                      {i18n.t('btn.cancel')}
                    </Text>
                  </View>
                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback
                  onPress={async () => {
                    if (!valueNm || !valueNm.trim()) {
                      return;
                    }
                    _onConfirm(valueNm.trim());
                    setValueNm('');
                    setModalUseStatus(null);
                  }}>
                  <View
                    style={[
                      styles.modalButtonStyle,
                      styles.modalCardBody,
                      styles.modalBoCard,
                      {
                        minWidth:nom.dp_px_198,
                        width:null,
                        paddingHorizontal:nom.dp_px_32,
                        backgroundColor: valueNm && valueNm.trim() ? '#000' : '#999',
                      },
                    ]}>
                    <Text
                      style={[
                        styles.fontSize_34,
                        {
                          fontWeight: '400',
                          color: '#fff',
                        },
                      ]}>
                      {modalUseStatus === 1
                        ? i18n.t('btn.create')
                        : i18n.t('btn.ok')}
                    </Text>
                  </View>
                </TouchableWithoutFeedback>
              </View>
            </View>
        </View>
      ) : null}
      <ModalStickerBtn
        modalVisible={modalStickerBtnVisible}
        onClose={() => {
          setModalStickerBtnVisible(false);
        }}
        screenWidth={screenWidth}
        screenHeight={screenHeight}
        onExport={async () => {
          setModalStickerBtnVisible(false);
          setModalUseStatus(42);
          setModalVisible(true);
          setModalTitle(i18n.t('title.export'));
          await _exportSticker();
        }}
        onDel={async () => {
          setModalStickerBtnVisible(false);
          try {
            let re = await SNUIUtils.showRattaDialog(
              i18n.t('msg.delColl'),
              i18n.t('btn.cancel'),
              i18n.t('btn.delete'),
              false
            );
            re ? stickerGroupDel([stickerGroupItem.id]) : null;

          } catch (e) {
            console.log("delet sticker error", e);
          }

          // setModalVisible(true);
          // setModalUseStatus(3);
          // setModalTitle(i18n.t('title.tips'));
          // setModalMessage(i18n.t('msg.delColl'));
        }}
        stickers={stickerItemList}
        onClearValueNm={() => setValueNm('')}
        onReset={() => {
          setModalStickerBtnVisible(false);
          setValueNm(stickerGroupItem?.name || '');
          setModalTitle(i18n.t('title.renameColl'));
          setModalMessage(i18n.t('placeholder.group'));
          setModalUseStatus(2);
          focusTextInput(true);
          /* InteractionManager.runAfterInteractions(() => {
            setTimeout(()=>{
              console.log("ModalStickerBtn textInputRef:"+textInputRef.current);
              if(textInputRef.current) {
                
                textInputRef?.current?.focus();
                textInputRef.current.setNativeProps({
                  selection: {
                    start: valueNm?.length,
                    end: valueNm?.length,
                  },
                });
              }
              
            },300);
          }); */
         
        }}
      />
      {isLoading ? (
        <View
          style={{
            width: '100%',
            height: '100%',
            position: 'absolute',
            top: 0,
            left: 0,
            zIndex: 9999,
            backgroundColor: '#ffffff',
          }}
        />
      ) : null}
      {isToast ? (
        <View
          style={{
            width: '100%',
            height: '100%',
            position: 'absolute',
            top: 0,
            left: 0,
            zIndex: 9999,
            backgroundColor: 'transparent',
            alignItems: 'center',
            justifyContent: rotation == 1 || rotation == 3 ? 'center' : null
          }}>
          <View
            style={{
              borderWidth: nom.dp_px_3,
              borderColor: 'black',
              backgroundColor:'white',
              height: nom.dp_px_120,
              width: null,
              paddingHorizontal: nom.dp_px_104,
              overflow: 'visible',
              justifyContent: 'center',
              alignItems: 'center',
              marginTop: rotation == 1 || rotation == 3 ? null : nom.dp_px_728

            }}

          >

            <Text style={{
              textAlign: 'center',
              flexShrink: 0,
              fontSize: nom.dp_px_34
            }} >{toastText}</Text>
          </View>


     </View>
      ) : null }

    </View>
  );
};

export default StickerBasePage;
